<template>
  <div class="dashboard-container">
    <!-- <div class="dashboard-text">name: {{ name }}</div> -->
    <el-card class="box-card">
      <!-- <h1 class="title">循环广播</h1> -->
      <!-- 表单 -->
      <div class="timeBox">
        <el-form ref="form" :model="form" :rules="Rules" label-width="170px">
          <!-- 基站ID -->
          <el-form-item label="基站" prop="checkedList">
            <template>
              <el-cascader
                v-model="form.checkedList"
                @change="checkedFn"
                :options="options"
                :props="props"
                collapse-tags
                clearable
              ></el-cascader>
            </template>
          </el-form-item>
           <!-- 播报间隔 -->
                  <el-form-item label="播报间隔" prop="interval">
                    <el-input
                      v-model="form.interval"
                      style="width: 80px"
                    ></el-input
                    >秒
                  </el-form-item>
                  <!-- 播报次数-->
                  <el-form-item
                    label="播报次数"
                    prop="times"
                  >
                    <el-input
                      v-model="form.times"
                      style="width: 80px"
                    ></el-input
                    >次数
                  </el-form-item>

          <el-form-item label="播报语音" prop="content">
            <div class="comtent">
              <el-input v-model="form.content" :disabled="true"></el-input>
              <el-button
                type="primary"
                icon="el-icon-s-order"
                @click="audioTextDlalog"
              ></el-button>
            </div>
          </el-form-item>

          <div class="sipButton">
            <el-button type="primary" @click="getSip('form')"
              >广播发送</el-button
            >
            <el-button icon="el-icon-refresh-left" @click="reset"
              >重置</el-button
            >
          </div>
        </el-form>
      </div>
    </el-card>
    <!-- 表格 -->
    <el-card class="box-card" style="margin-top: 20px">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="call_name" label="广播频道" width="200">
          <template slot-scope="props">
            <el-popover
              placement="top-start"
              title="广播频道"
              width="200"
              trigger="hover"
              :content="props.row.call_name"
            >
              <div slot="reference" v-if="props.row.call_name !== undefined">
                {{ props.row.call_name.slice(0, 20) }}
              </div>

              <div slot="reference" v-else>
                {{ props.row.call_name }}
              </div>
            </el-popover>
          </template>
        </el-table-column>

        <el-table-column label="开始时间" width="140">
          <template slot-scope="scope">
            {{
              $moment(scope.row.start_time * 1000).format("YYYY-MM-DD/HH:mm")
            }}
          </template>
        </el-table-column>
        <el-table-column prop="" label="播报次数" width="120">
              <template slot-scope="scope">
                <span>
                  {{ scope.row.played_times }}
                </span>
              </template>
            </el-table-column>
             <el-table-column prop="" label="播报间隔" width="120">
              <template slot-scope="scope">
                <span>
                  {{ scope.row.interval + "秒" }}
                </span>
              </template>
            </el-table-column>
        <el-table-column prop="" label="广播状态" width="120">
          <template slot-scope="scope">
                <span
                  class="el-icon-success"
                  style="color: #13ce66"
                  v-if="scope.row.status === 1"
                ></span>
                <span
                  class="el-icon-warning"
                  style="color: #fbdc3c"
                  v-if="scope.row.status === 0"
                ></span>
                <span
                  class="el-icon-circle-close"
                  style="color: #ff4949"
                  v-if="scope.row.status === -1"
                ></span>
                <span>
                  {{
                    scope.row.status === 1
                      ? "已播放"
                      : scope.row.status === 0
                      ? "未播放"
                      : scope.row.status === -1
                      ? "出错"
                      :  ""
                  }}
                </span>
              </template>
        </el-table-column>
        <el-table-column prop="" label="操作">
          <template slot="header" slot-scope="scope">
            <div class="excel-btn">
              <el-button
                type="success"
                style="margin-left: 85%"
                @click="exportToExcel"
                >导出</el-button
              >
            </div>
          </template>
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="del(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

         <!-- 分页 -->
          <el-pagination
            layout="prev, pager, next"
            :page-count="paging.total"
            @current-change="page_change"
          >
          </el-pagination>
        </el-tab-pane>
    </el-card>

    <VoiceText
      :dialogVisible="voiceTextDialogVisible"
      @update:dialogVisible="handleDialogVisibleChange"
      @upload="upload"
    ></VoiceText>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { sendSipData, ajaxInitiator,  sipLoopSend,CycleTable,sipUser,cyCleTableDel} from "@/api/sip";
import { Message } from "element-ui";
import { parse } from "path-to-regexp";
import * as XLSX from "xlsx";
import VoiceText from "../sipComponents/index.vue";
export default {
  name: "Dashboard",
  components: {
    VoiceText,
  },
  created() {
    this.sip_init();
    this.ajaxsendTableInit();
  },
  data() {
    return {
      props: { multiple: true },
      tableData: [],
      // 分页
      paging: {
        pag: 1,
        limit: 10,
        total: 100,
      },
      //音频对话框
      voiceTextDialogVisible: false,
      intervalId: "",
      //获取sip发起地数据
      callData: [],
      //服务器配置参数
      sipForm: {},
      //频道全选
      checked: false,
      options: [],
      // 定时参数
      form: {
        sip_ip: "",
        sip_port: "",
        user_id: "",
        password: "",
        call_id: "",
        content: "",
        interval:"", //播报间隔
        times:"", //播报次数
        path: "", //播放语音路径
        checkedList:[]
      },
      // 定时参数必填规则
      Rules: {
        times: [
          { required: true, message: "播报次数不能为空", trigger: "blur" },
        ],
        interval: [
          { required: true, message: "播报间隔不能为空", trigger: "blur" },
        ],
        content: [
          {
            required: true,
            message: "播报语音不能为空",
            trigger: "blur",
          },
        ],
        checkedList: [
          { required: true, message: "请选择基站", trigger: "blur" },
        ],
      },
      loading: false,
    };
  },
  computed: {
    ...mapGetters(["name"]),
  },
  methods: {
     // 分页
    page_change(data) {
      this.ajaxsendTableInit(data)
    },
    getSip(formName) {

      if (Number(this.form.interval) > 60) {
        this.$message.warning("间隔不能大于60秒");
        return
      }

      this.$refs[formName].validate( async(valid) => {
        if (valid === false) {
          return
        } else {
           const res = await sipLoopSend({
        sip_ip: this.form.sip_ip,
        sip_port: this.form.sip_port,
        user_id: this.form.user_id,
        call_id: this.form.call_id,
        times: this.form.times,
        interval: this.form.interval,
        password: '',
        name: this.form.content,
      });

      if (res.data.status_code ===  0) {
        this.$message.success("广播生成");
        this.ajaxsendTableInit(1);
      }
        }
      });


    },
    async sip_init() {
      let result = await sipUser()

      let sipuserData = result.data.data.rows[0];

      this.form.user_id = String(sipuserData.user_id);
      this.form.password = sipuserData.password;
    },
    async ajaxsendTableInit(pag) {
      let name = JSON.parse(localStorage.getItem("HSKJ-username"));
      const res = await ajaxInitiator({ userChanne: name });

      let ids = res.data.meta.data.map((item) => {
        return item.Initiator_id;
      });

      this.ajaxInitiatorName = res.data.meta.data;
      // // 处理成element ui 使用的格式

      this.ajaxInitiatorName.forEach((item) => {
        item.label = item.Initiator_name;
        item.value = {
          ip: item.ip_gateway,
          port: item.port,
          callId: item.Initiator_id,
        };
      });

      let CH14_list = this.ajaxInitiatorName.filter((item) => {
        return item.channel === "CH14";
      });
      let CH16_list = this.ajaxInitiatorName.filter((item) => {
        return item.channel === "CH16";
      });
      let CH0_list = this.ajaxInitiatorName.filter((item) => {
        return item.channel === "CH0";
      });
      this.options = [
        {
          value: "CH14",
          label: "CH14",
          children: CH14_list,
        },
        {
          value: "CH16",
          label: "CH16",
          children: CH16_list,
        },
        {
          value: "CH0",
          label: "CH0",
          children: CH0_list,
        },
      ];

      let  ressult = await CycleTable({pag: pag || 1, call_ids: ids })

      this.tableData = ressult.data.data.rows;

      this.paging.total = ressult.data.data.total;

      //循环匹配发起地
      this.tableData.forEach((item) => {
        let calliIdName = [];
        this.ajaxInitiatorName.forEach((elemnt) => {
          if (Number(item.call_id) === elemnt.Initiator_id) {
            item.call_name = elemnt.Initiator_name;
          }

          let calliIdList = item.call_id.split("@");

          if (calliIdList.length >= 2) {
            calliIdList.forEach((val) => {
              if (Number(val) === elemnt.Initiator_id) {
                calliIdName.push(elemnt.Initiator_name);
              }
            });
            item.call_name = calliIdName.join("@");
          }
        });
      });
    },
    reset() {
      this.form.sip_ip = ""
      this.form.sip_port = ""
      this.form.call_id = ""
      this.form.sip_ip = ""
      this.form.content = ""
      this.form.path = ""
      this.form.radio = "2"
      this.form.checkedList = []
      console.log(253,this.form.interval);
    },

    // // 基站全选
    checkedFn(data) {
      this.form.checkedList = data;
      //提取网关ip
      this.form.sip_ip = this.form.checkedList.map((item) => item[1].ip);
      this.form.sip_port = this.form.checkedList.map((item) => item[1].port);
      this.form.call_id = this.form.checkedList.map((item) =>
        String(item[1].callId)
      );

      if (this.form.sip_ip.length >= 2) {
        this.form.sip_ip = this.form.sip_ip.join("@");
      } else {
        this.form.sip_ip = this.form.sip_ip[0];
      }

      if (this.form.sip_port.length >= 2) {
        this.form.sip_port = this.form.sip_port.join("@");
      } else {
        this.form.sip_port = this.form.sip_port[0];
      }

      if (this.form.call_id.length >= 2) {
        this.form.call_id = this.form.call_id.join("@");
      } else {
        this.form.call_id = this.form.call_id[0];
      }
    },
    //打开音频对话框
    audioTextDlalog() {
      this.voiceTextDialogVisible = true;
    },
    handleDialogVisibleChange(newValue) {
      this.voiceTextDialogVisible = newValue;
    },
    //接收音频子组件返回值
    upload(newValue) {
      this.form.content = newValue.name;
    },
     // 导出excel
    exportToExcel() {
      // 直接使用XLSX的内置导出方法
      const ws = XLSX.utils.json_to_sheet(
        this.tableData.map((item) => ({
          广播频道: item.call_name,
          开始时间: this.$moment(item.start_time * 1000).format(
            "YYYY-MM-DD/HH:mm"
          ),
          播报次数:item.played_times,
          播报间隔:item.interval+"秒",
          广播状态:
            item.status === 0 ? "未播放" : item.status === 1 ? "已播放" : "",
        }))
      );

      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "定时表格");

      // 直接导出文件（不需要file-saver）
      XLSX.writeFile(wb, "循环播报表格.xlsx");
    },
     async del(data) {
      let res =  await cyCleTableDel({ id: String(data.id)});
      if (res.data.meta.code === 200) {
         Message.success("删除成功");
         this.ajaxsendTableInit(1)
      }

    },
  },
};
</script>

<style lang="scss" scoped>
.el-input {
  width: 88%;
}
.comtent {
  display: flex;
}
.sipButton {
  display: flex;
  justify-content: center;
}
.title {
  text-align: center;
}
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>
